from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, reverse, HttpResponse
from django.conf import settings
import re


class AuthMd(MiddlewareMixin):


    def process_request(self, request):

        # 获取访问当前页面的URL
        url_path = request.path_info

        # 判断当前URL是否在白名单
        for item in settings.AUTH_WHITE_URL:
            if url_path == item:
                return None

        # 从session中获取user
        obj = request.session.get('user')

        # 判断是否存在
        if obj:
            request.user = obj
        else:
            return redirect(reverse('login'))

        # 判断是否有权限访问当前页面
        # 获取
        permission_list = request.session.get(settings.PERMISSION_SESSION_KEY)
        # 判断当前url是否在
        # if url_path in permission_list:
        #     return None
        # else:
        #     return HttpResponse('您无权访问该页面！')

        for item in permission_list:

            if url_path == item:
                return None

            match_result = re.match(item, url_path)
            if match_result:
                return None

            # 拼接正则表表达式的字符串
            re_str = '^' + item + "(edit/|add/|edit/|list/)$"
            match_result = re.match(re_str, url_path)
            if match_result:
                return None
        return HttpResponse('您无权访问该页面！')
